package com.lv.jie.service.impl;

import com.lv.jie.mapper.UserMapper;
import com.lv.jie.pojo.User;
import com.lv.jie.service.UserService;
import com.lv.jie.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 24694
 */
@Service("usersService")
public class UserServiceImpl implements UserService {
    final UserMapper userMapper;
    final JavaMailSenderImpl mailSender;
    final RedisTemplate redisTemplate;

    UserServiceImpl(UserMapper userMapper, RedisTemplate redisTemplate, JavaMailSenderImpl mailSender){
        this.mailSender = mailSender;
        this.redisTemplate = redisTemplate;
        this.userMapper = userMapper;
    }

    @Override
    public JsonResult sendVerificationCode(String email) {
        String i = (int) ((Math.random() * 9 + 1) * 100000) + "";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("登录验证码");
        message.setText("验证码为：" + i );
        message.setTo(email);
        message.setFrom("2469478718@qq.com");
        mailSender.send(message);
        redisTemplate.opsForValue().set(email, i,5, TimeUnit.MINUTES);
        return new JsonResult("发送成功");
    }

    @Override
    public JsonResult confirm(String email, String code) {
        Object redisCode = redisTemplate.opsForValue().get(email);

        if (redisCode != null && redisCode.equals(code)){
            User user = userMapper.selectByEmail(email);
            if (user == null){
                int id = (int) ((Math.random() * 9 + 1) * 1000);
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss " );
                String nowTime = sdf.format(date);
                try {
                    Date time = sdf.parse(nowTime);
                    User user1 = new User(null, "小杰杰" + id, null, null, email, null, 1, time);
                    if (userMapper.insertSelective(user1) != 1){
                        return new JsonResult("插入失败请联系管理员", 500);
                    }
                    setToken(email,user1.getId()+ "-" + code);
                    return new JsonResult(user1.getId()+  "-" + code);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (Objects.requireNonNull(user).getStatus() == 0){
                return new JsonResult("用户已被注销",404);
            }

            setToken(email, Objects.requireNonNull(user).getId() + "-" + code);
            return new JsonResult(Objects.requireNonNull(user).getId() + "-" + code);
        }
        return new JsonResult("验证码错误", 501);
    }

    @Override
    public JsonResult selectUserById(Integer id, String token) {
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user != null){
            return new JsonResult(user);
        }
        return new JsonResult("用户不存在",404);
    }

    @Override
    public JsonResult updateUser(User user, String token) {
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        if (userMapper.updateByPrimaryKeySelective(user) == 1){
            return new JsonResult("修改成功");
        }
        return new JsonResult("修改失败请联系管理员",500);
    }

    private void setToken(String email, String token){
        redisTemplate.opsForValue().set(token, email,2, TimeUnit.HOURS);
    }

    private boolean getToken(String token){
        boolean flag = false;
        Object redisCode = redisTemplate.opsForValue().get(token);
        if (redisCode != null){
            flag = true;
        }
        return !flag;
    }
}
